import requests
import time
import json
import os
from PIL import Image, ImageEnhance
from paddleocr import PaddleOCR
def ocr_space_file(filename, overlay=False, api_key='e61f4d4c3488957', language='eng'):
    """ OCR.space API request with local file.
        Python3.5 - not tested on 2.7
    :param filename: Your file path & name.
    :param overlay: Is OCR.space overlay required in your response.
                    Defaults to False.
    :param api_key: OCR.space API key.
                    Defaults to 'helloworld'.
    :param language: Language code to be used in OCR.
                    List of available language codes can be found on https://ocr.space/OCRAPI
                    Defaults to 'en'.
    :return: Result in JSON format.
    """

    payload = {'isOverlayRequired': overlay,
               'apikey': api_key,
               'language': language,
               }
    with open(filename, 'rb') as f:
        r = requests.post('https://api.ocr.space/parse/image',
                          files={filename: f},
                          data=payload,
                          )
    return r.content.decode()

def ocr_result(image_path):
    ocr = PaddleOCR(use_angle_cls=True, lang='ch')
    result = ocr.ocr(image_path, cls=True)
    word_infos = []
    word_dict = None
    # visit every word
    for word in result:
        word_dict = dict()
        word_dict["text"] = word[1][0]
        top = word[0][0][1]
        left = word[0][0][0]
        bottom = word[0][2][1]
        right = word[0][2][0]
        word_dict["boundingBox"] = [left ,top ,0 ,0, right, bottom]
        word_infos.append(word_dict)
    return word_infos

if __name__ == "__main__":
    image_path = 'C:\\work\\evalset_fqa\\vbar\\bitmap\\'
    image_names = os.listdir(image_path)
    for name in ['495.jpg', '151,jpg']:
        image_file_path = os.path.join(image_path, name)
        result = ocr_result(image_file_path)
        print(result)
